package com.hotline.monitor.service.agent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hotline.monitor.constant.Constants;
import com.hotline.monitor.dto.AgentDTO;
import com.hotline.monitor.dto.AgentStatusDTO;
import com.hotline.monitor.enums.ReturnCodeEnum;
import com.hotline.monitor.enums.SkillMediaTypeEnum;
import com.hotline.monitor.util.HttpUtils;
import com.hotline.monitor.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.*;

@Service
@Slf4j
public class AgentGroupServiceImpl implements AgentGroupService{

    private static final String URI_ONLINE_AGENT_ON_VDN = "/agentgateway/resource/agentgroup/{}/allonlineagents";

    @Autowired
    private OnlineAgentService onlineAgentService;

    @Value("${hotline.url}")
    private String url;

    @Value("${agent.worknumber}")
    private String workNumber;

    @Override
    public List<AgentStatusDTO> onlineAgentOnVdn() {
        String reqUrl = url + URI_ONLINE_AGENT_ON_VDN;

        reqUrl = StringUtils.format(reqUrl,workNumber);
        Map<String, String> header = new HashMap<>();

        log.info("Guid：{}",Constants.HEADER_GUID);
        header.put("Guid", Constants.HEADER_GUID);
        String resultString = HttpUtils.doGet(reqUrl,null,header);
        log.info("查询坐席状态信息返回：{}",resultString);

        JSONObject resultObject = JSON.parseObject(resultString);
        String retCode = resultObject.getString("retcode");
        JSONArray resultJsonArray = resultObject.getJSONArray("result");

        List<AgentStatusDTO> agentStatusList = new ArrayList();

        if(ReturnCodeEnum.NOT_LOGIN.getCode().equals(retCode) ||
                ReturnCodeEnum.NO_RIGHT.getCode().equals(retCode)){
            String guid = onlineAgentService.login();
            Constants.HEADER_GUID = guid;
            return Collections.EMPTY_LIST;
        }else if(ReturnCodeEnum.SUCCESS.getCode().equals(retCode) && Objects.nonNull(resultJsonArray)){
            List<AgentDTO> agentList = JSON.parseArray(JSON.toJSONString(resultJsonArray),AgentDTO.class);
            for (AgentDTO agentDTO : agentList){
                if(StringUtils.equals(agentDTO.getSkillMediaType(), SkillMediaTypeEnum.VIDEO_ALLS.getCode())){
                    agentStatusList.addAll(agentDTO.getAgent());
                }
            }
            return agentStatusList;
        }
        return Collections.EMPTY_LIST;
    }
}
